package com.suning.sawp.in.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.dto.common.EmployeeInfo;
import com.suning.sawp.dto.common.OrgInfo;
import com.suning.sawp.dto.common.QueryResult;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.precharge.CommonRtn;
import com.suning.sawp.in.filter.RequestUserHolder;
import com.suning.sawp.intf.bind.BindDeviceService;
import com.suning.sawp.intf.bind.dto.BindDeviceInfoDto;
import com.suning.sawp.intf.bind.dto.BindOperationDto;
import com.suning.sawp.intf.bind.dto.BindRecordDto;
import com.suning.sawp.intf.model.ModelErrorConstant;

/**
 * 〈工号绑定设备后台控制类〉<br>
 * 〈功能详细描述〉
 *
 * @author 17061157
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/adminPage/bindDevice")
public class BindDeviceController extends DjBaseController {

	private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);
	
	private static final String END_TIME_SUFFIXES = " 23:59:59";

	private static final String FAIL = "0";

	private static final String SUCCESS = "1";

	@Autowired
	BindDeviceService bindDeviceService;

	/**
	 * 
	 * 功能描述:查询绑定设备信息列表 <br>
	 * 〈功能详细描述〉
	 *
	 * @param staffId
	 * @param store
	 * @param startTime
	 * @param endTime
	 * @param pageNo
	 * @param pageLimit
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/queryBindInfos.do")
	public MyGsonView queryBindInfos(String storeId, Integer lockStatus, Integer whitelistSts, String staffId,
			String startTime, String endTime, Integer pageNo, Integer pageSize) {
		ReturnMsg<QueryResult<BindDeviceInfoDto>> ret = new ReturnMsg<QueryResult<BindDeviceInfoDto>>();

		EmployeeInfo requestUser = RequestUserHolder.getRequestUser();
		// 获取登录人的机构编码
		String organCode = getOrganCode(requestUser);
		if (StringUtils.isBlank(organCode) 
				&& !OrgInfo.ORG_LEVEL.HQ_LEVEL.equals(requestUser.getOrgLevel())) {
			ret.setError(FAIL, "当前登录人没有所属机构");
			return setGsonView(ret);
		}
		
		// 查询管辖范围内所有员工的绑定设备信息列表
		try {
			Map<String, Object> queryMap = new HashMap<String, Object>();
			queryMap.put("organLevel", requestUser.getOrgLevel());
			queryMap.put("organCode", organCode);
			queryMap.put("storeId", storeId);
			queryMap.put("staffId", staffId);
			queryMap.put("lockStatus", lockStatus);
			queryMap.put("whitelistSts", whitelistSts);
			queryMap.put("startTime", startTime);
			queryMap.put("endTime", StringUtils.isNotBlank(endTime) ?  endTime + END_TIME_SUFFIXES : null);
			ret = bindDeviceService.queryBindInfoList(queryMap, pageNo, pageSize);
		} catch (Exception e) {
			ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
			LOGGER.error(String.format(
					"BindDeviceController queryBindInfos param(store:%s,staffId:%s,lockStatus:%s,whiteStatus:%s,startTime:%s,endTime:%s)",
					storeId, staffId, lockStatus, whitelistSts, startTime, endTime), e);
		}
		return setGsonView(ret);
	}

	/**
	 * 获取用户的机构代码（最低一级机构代码）
	 * @param requestUser
	 * @return
	 */
	private String getOrganCode(EmployeeInfo requestUser) {
		String organCode = requestUser.getStoreCode();
		if (StringUtils.isBlank(organCode)) {
			organCode = requestUser.getBranchCode();
			if (StringUtils.isBlank(organCode)) {
				organCode = requestUser.getRegion5Code();
			}
		}
		return organCode;
	}
	
	/**
	 * 
	 * 功能描述:后台操作历史查询 <br>
	 * 〈查询指定员工的绑定设备在后台的操作历史记录〉
	 *
	 * @param staffId
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/queryBindOperationHis.do")
	public MyGsonView queryBindOperationHis(String staffId) {
		ReturnMsg<QueryResult<BindOperationDto>> ret = new ReturnMsg<QueryResult<BindOperationDto>>();
		
		try {
			ret = bindDeviceService.queryBindOperationHis(staffId);
		} catch (Exception e) {
			ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
			LOGGER.error(String.format("BindDeviceController queryBindOperationHis param(staffId:%s)", staffId), e);
		}
		return setGsonView(ret);
	}
	
	/**
	 * 
	 * 功能描述:员工绑定记录查询 <br>
	 * 〈查询指定员工绑定过的设备的历史记录〉
	 *
	 * @param staffId
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/queryBindHistory.do")
	public MyGsonView queryBindHistory(String staffId) {
		ReturnMsg<QueryResult<BindRecordDto>> ret = new ReturnMsg<QueryResult<BindRecordDto>>();
		
		try {
			ret = bindDeviceService.queryBindHistory(staffId);
		} catch (Exception e) {
			ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
			LOGGER.error(String.format("BindDeviceController queryBindHistory param(staffId:%s)", staffId), e);
		}
		return setGsonView(ret);
	}

	/**
	 * 
	 * 功能描述:移除白名单操作 <br>
	 * 〈功能详细描述〉
	 *
	 * @param staffId
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/removeWhitelist.do")
	public MyGsonView removeWhitelist(String staffId) {
		ReturnMsg<CommonRtn> ret = new ReturnMsg<CommonRtn>();
		
		EmployeeInfo requestUser = RequestUserHolder.getRequestUser();
		String operatorId = requestUser.getStaffId();
		String operatorName = requestUser.getStaffName();
		
		try {
			// 未在白名单，不可执行移出操作
			if (!bindDeviceService.queryWhitelistStatus(staffId)) {
				ret.setError(ErrorCodeConstants.ERR_0052, ErrorCodeConstants.ERR_MAP);
			} else {
				bindDeviceService.removeWhitelist(staffId, operatorId, operatorName);
				ret.setRetFlag(SUCCESS);
			}
		} catch (Exception e) {
			ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
			LOGGER.error(String.format("BindDeviceController removeWhitelist param(staffId:%s)", staffId), e);
		}
		return setGsonView(ret);
	}
	
	/**
	 * 
	 * 功能描述:添加白名单操作 <br>
	 * 〈功能详细描述〉
	 *
	 * @param staffId
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/addWhitelist.do")
	public MyGsonView addWhitelist(String staffId) {
		ReturnMsg<CommonRtn> ret = new ReturnMsg<CommonRtn>();
		EmployeeInfo requestUser = RequestUserHolder.getRequestUser();
		String operatorId = requestUser.getStaffId();
		String operatorName = requestUser.getStaffName();
		
		try {
			// 已在白名单，不可执行添加操作
			if (bindDeviceService.queryWhitelistStatus(staffId)) {
				ret.setError(ErrorCodeConstants.ERR_0051, ErrorCodeConstants.ERR_MAP);
			} else {
				bindDeviceService.addWhitelist(staffId, operatorId, operatorName);
				ret.setRetFlag(SUCCESS);
			}
		} catch (Exception e) {
			ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
			LOGGER.error(String.format("BindDeviceController addWhitelist param(staffId:%s)", staffId), e);
		}
		return setGsonView(ret);
	}
	
	/**
	 * 
	 * 功能描述:处理解锁申请 <br>
	 * 〈功能详细描述〉
	 *
	 * @param staffId
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/handleUnlockApply.do")
	public MyGsonView handleUnlockApply(String staffId, String operateType, String deviceId, String reason) {
		ReturnMsg<CommonRtn> ret = new ReturnMsg<CommonRtn>();
		ret.setRetFlag(SUCCESS);
		
		EmployeeInfo requestUser = RequestUserHolder.getRequestUser();
		String operatorId = requestUser.getStaffId();
		String operatorName = requestUser.getStaffName();
		
		// 当前用户是否在白名单
		if (bindDeviceService.queryWhitelistStatus(staffId)) {
			ret.setError(ErrorCodeConstants.ERR_0051, ErrorCodeConstants.ERR_MAP);
			return setGsonView(ret);
		}
				
		try {
			if ("1".equals(operateType)) {
				// 解锁
				bindDeviceService.UnlockLockedStaff(staffId, deviceId, operatorId, operatorName);
			} else if ("2".equals(operateType)) {
				// 驳回
				bindDeviceService.RejectUnlockedApply(staffId, deviceId, reason, operatorId, operatorName);
			} else {
				ret.setError(FAIL, "非法操作类型");
			}
		} catch (Exception e) {
			ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
			LOGGER.error(String.format("BindDeviceController handleUnlockApply param(staffId:%s)", staffId), e);
		}
		return setGsonView(ret);
	}
	
}
